<template>
<el-button
    :disabled="loading"
    slot="trigger"
    icon="el-icon-top-right"
    size="mini"
    @click="handleClick"
    type="default"
    :circle="circle">
  <span v-if="!circle">导出</span>
</el-button>
</template>
<script type="text/javascript">
export default {
  props: ['api', 'params', 'fileName','circle'],
  data () {
    return {        
      filter: {page: 1, pagesize: 200},
      loading: false
    }
  },
  methods: {
    handleClick () {
      let that = this
      let csvContent = 'data:text/csv;charset=utf-8,\ufeff'
      let SPT = ','
      let getpage = function (page) {
        that.$api.get(that.api, Object.assign(that.params, that.filter)).then((res) => {
          if (res.status === 1) {
            if (res.data.list && res.data.list.length > 0) {
              if (res.data.fields && page === 1) {
                csvContent += res.data.fields.join(SPT) + '\n'
              }
              res.data.list.forEach((row) => {
                let r = []
                for (let i in row) {
                  r.push(row[i])
                }
                csvContent += r.join(SPT) + '\n'
              })
              if (res.totalpage > 1 && page < res.totalpage) {
                setTimeout(function () {
                  getpage(page + 1)
                }, 50)                
              } else {
                that.loading = false
                that.saveFile(csvContent)                
              }
            }
          }
        })
      }
      that.loading = true
      getpage(1)      
    },
    saveFile (csvContent) {
      let el = document.createElement('a')
      el.href = encodeURI(csvContent)
      el.download = this.fileName + '.csv'
      el.click()
      el.remove()
    }
  }
}
</script>
</style>